﻿using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Book.JWT
{
    public class JwtService : IJwtService
    {
        private readonly IConfiguration _configuration;

        public JwtService(IConfiguration configuration)
        {
            this._configuration = configuration;
        }

        public string GetToken()
        {
            //1：验证用户名和密码

            //2: 创建jwt   jwt 由3部分进行
            // header
            var signingAlgorithm = SecurityAlgorithms.HmacSha256;
            // payload
            var claims = new[]{
            new Claim(JwtRegisteredClaimNames.Sub,"username")
        };

            // signiture

            //下面是jwt需要的参数

            //取数字签名的密钥
            var secret = _configuration["Authentication:SecretKey"];
            //进行转码
            var secretByte = Encoding.UTF8.GetBytes(secret);
            var signingKey = new SymmetricSecurityKey(secretByte);

            var signingCredentials = new SigningCredentials(signingKey, signingAlgorithm);

            var token = new JwtSecurityToken(
                issuer: _configuration["Authentication:Issuer"],//谁发布的token
                audience: _configuration["Authentication:Audience"],//这个token发布给谁
                claims,//payload
                notBefore: DateTime.UtcNow,//发布时间
                expires: DateTime.UtcNow.AddDays(1),//有效时间
                signingCredentials //数据前面
            );

            var tokenJson = new JwtSecurityTokenHandler().WriteToken(token);

            //3：OK+ Jwt
            return tokenJson;
        }
    }
}
